<template>
  <el-input v-model.number="formValue" v-bind="$attrs" type="number" @input="handleInput">
    <template v-if="unit" slot="append">{{defaultUnit}}</template>
    <el-select
      v-else
      slot="append"
      v-model="defaultUnit"
      :style="{ width: '66px' }"
      @input="handleInput"
    >
      <el-option v-for="unit in units" :key="unit" :label="unit" :value="unit" />
    </el-select>
  </el-input>
</template>

<script>
export default {
  name: "InputNumber",
  props: {
    value: {
      type: [Number, String],
      default: "",
    },
    unit: {
      type: String,
      default: "",
    },
    units: {
      type: Array,
      default: () => ["px", "em", "rem", "%"],
    },
  },

  data() {
    return {
      formValue: "",
      defaultUnit: "",
    };
  },

  watch: {
    value(newValue) {
      this.formValue = "";
      this.defaultUnit = this.unit || this.units[0];
      if (newValue) {
        this.splitNumberAndNonNumber(this.value);
      }
    },
  },
  mounted() {
    this.splitNumberAndNonNumber(this.value);
  },
  methods: {
    handleInput() {
      let value = "";
      if (this.formValue !== "") value = this.formValue + this.defaultUnit;
      this.$emit("input", value);
    },
    splitNumberAndNonNumber(str) {
      if (!str) {
        this.formValue = str;
        this.defaultUnit = this.unit || this.units[0];
        return;
      }
      // 使用正则表达式匹配所有数字部分和非数字部分
      const regex = /^(\d+)([^\d]+)$/;
      const matches = str.match(regex);
      if (matches) {
        this.formValue = matches[1];
        this.defaultUnit = matches[2];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>